﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace ClassLibrary1.entity
{
    [XmlRoot("client")]
   public class Client:BaseEntity
    {
       [XmlElement("book")]
       public Booking booking { get; set; }

       [XmlElement("cargo")]
       public Cargo cargo { get; set; }

       [XmlElement("name")]
       public string name { get; set; }
       
       public Client()  
        {
            int id = 1;

            while (true)
            {
                var entity = FindById(id.ToString());
                if (entity == null)
                {
                    this.id = id;
                    return;
                }
                id++;
            }
        }

        public Client(string id)
        {
            if (Client.FindById(id) != null) return;
            int.TryParse(id, out this.id);
        }

        public Client(string[] mas)
        {
            this.id = new Client(mas[0]).id;
            Upd(mas.Skip(1).ToArray());
        }

        public static Client FindById(string id)
        {
            return (Client)Data.entity.FirstOrDefault(item => item.GetType() == typeof(Client) && item.id == int.Parse(id));
        }

        public static List<BaseEntity> FindAll()
        {
            return Data.entity.FindAll(item => item.GetType() == typeof(Client));
        }

        public override void Upd(string[] mas)
        {
            try { this.name = mas[0]; }
            catch (Exception) { }
            try { 
                this.cargo = Cargo.FindById(mas[1]);
                if (this.cargo != null) this.cargo.client = this;
            }
            catch (Exception) { }
            try { 
                this.booking = Booking.FindById(mas[2]);
                if (this.booking != null) this.booking.client = this;
            }
            catch (Exception) { }
            
        }

        public bool Equals(Booking a)
        {
            if (this.id.Equals(a.id)) return true;
            return false;
        }

        public override string Write()
        {
            string s = "client" + " " + this.id;
            s += " ";
            if (this.name != null) s += this.name.ToString();
            s += " ";
            if (this.cargo != null) s += this.cargo.id.ToString();
            s += " ";
            if (this.booking != null) s += this.booking.id.ToString();
            return s;
        }

    }
}
